package com.changgou.goods.service.Impl;

import com.changgou.goods.dao.BrandMapper;
import com.changgou.goods.service.BrandService;
import com.changgou.pojo.Brand;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * @ClassName BrandServiceImpl
 * @Description: TODO
 * @Author 郑乾
 * @Date 2020-08-01
 * @Version V1.0
 **/
@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;

    @Override
    public List<Brand> findAll() {
        return brandMapper.selectAll();
    }

    @Override
    public Brand findById(int id) {

        return brandMapper.selectByPrimaryKey(id);
    }

    @Override
    public void add(Brand brand) {
        brandMapper.insert(brand);
    }

    @Override
    public void update(Brand brand) {
        brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public void delete(int id) {
        brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Page<Brand> search(Integer pageNum, Integer pageSize, Map<String, Object> searchMap) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = createExample(searchMap);
        Page<Brand> brands = (Page<Brand>) brandMapper.selectByExample(example);
        return brands;
    }

    private Example createExample(Map<String, Object> searchMap) {
        //多条件查询
        Example example = new Example(Brand.class);
        if (!CollectionUtils.isEmpty(searchMap)) {
            //封装查询条件
            Example.Criteria criteria = example.createCriteria();
            String name = (String) searchMap.get("name");
            if (StringUtils.isEmpty(name)) {
                criteria.andLike("name", "%" + name + "%");
            }
            String id = (String) searchMap.get("id");
            if (null != id) {
                criteria.andEqualTo("id", id);
            }
        }
        return example;
    }
}
